<template>
  <avue-crud :option="option"
             :data="data"
             :summary-method="summaryMethod"
             @selection-change="selectionChange"></avue-crud>
</template>
<script>
export default {
  data () {
    return {
      selectList: [],
      data: [
        {
          sum: 5,
          avg: 10,
          count: 2,
        }, {
          sum: 15,
          avg: 20,
          count: 1,
        }
      ],
      option: {
        selection: true,
        index: true,
        showSummary: true,
        column: [{
          label: '相加',
          prop: 'sum'
        },
        {
          label: '平均值',
          prop: 'avg'
        },
        {
          label: '统计',
          prop: 'count'
        }]
      }
    }
  },
  methods: {
    selectionChange (list) {
      this.selectList = list;
    },
    summaryMethod ({ columns, data }) {
      const sums = [];
      if (columns.length > 0) {
        columns.forEach((column, index) => {
          let prop = column.property
          if (['sum', 'avg', 'count'].includes(prop)) {
            let values = this.selectList.map(item => Number(item[prop] || 0));
            let all = values.length !== 0 ? sums[index] = values.reduce((a, b) => {
              return a + b;
            }) : 0
            if (prop == 'sum') {
              sums[index] = all
            } else if (prop == 'avg') {
              sums[index] = all / values.length || 0
            } else if (prop == 'count') {
              sums[index] = values.length
            }
          } else {
            sums[index] = '-'
          }
        });
      }
      return sums;
    }
  }
}
</script>